package com.naiterui.ehp.bs.pc.modules.security.service;

import com.naiterui.ehp.bp.bo.doctor.PcUserBO;
import com.naiterui.ehp.bs.pc.common.constants.CacheConstants;
import com.naiterui.ehp.bs.pc.common.utils.JwtUser;
import com.naiterui.ehp.bs.pc.modules.sys.feign.IDoctorFeignClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.lang.NonNull;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;

@Slf4j
@Service
@RequiredArgsConstructor
public class JwtUserDetailsServiceImpl implements UserDetailsService {

    private final IDoctorFeignClient doctorFeignClient;

    @Override
    @Cacheable(value = CacheConstants.USER, key = "#username")
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public UserDetails loadUserByUsername(@NonNull String username) {
        PcUserBO user;
        try {
            user = doctorFeignClient.getUserInfo(username);
            return JwtUser.builder()
                    .id(user.getUserId())
                    .username(user.getPhone())
                    .name(user.getName())
                    .mobile(user.getPhone())
                    .password(user.getSalt() + "~" + user.getPassword())
                    .enabled(user.getAccountStatus() != 1)
                    .authorities(Collections.emptySet())
                    .permissions(Collections.emptySet())
                    .roleIdList(Collections.emptyList())
                    .build();
        } catch (Exception e) {
            return null;
        }
    }
}
